﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LitJson;

[AddComponentMenu("PUEX/Affector/Size/ScaleBySpeed")]
public class PUEXScaleBySpeedAffector : PUEXAffector {

	#region - Editable property
	public PUEXDynamicAttribute scaleXBySpeed;
	public PUEXDynamicAttribute scaleYBySpeed;
	public float speedRangeMin;
	public float speedRangeMax;
	#endregion
	
	#region - Lifecycle
	public PUEXScaleBySpeedAffector ()
	{
		scaleXBySpeed = PUEXDynamicAttribute.GenerateFixed (1f);
		scaleYBySpeed = PUEXDynamicAttribute.GenerateFixed (1f);
		speedRangeMin = 0f;
		speedRangeMax = 1f;
	}
	
	public override void enable () {
		if (speedRangeMin > speedRangeMax) {
			float tmp = speedRangeMin;
			speedRangeMin = speedRangeMax;
			speedRangeMax = tmp;
		}
		
		base.enable ();
	}
	#endregion
	
	#region - Update
	public override void update (float dt, PUEXParticle particle)
	{		
		float t = 0f;
		float absSpeed = Mathf.Abs (particle.speed);
		if (absSpeed < speedRangeMin) {
			t = 0f;
		} else if (absSpeed > speedRangeMax) {
			t = 1f;
		} else {
			t = (absSpeed - speedRangeMin) / (speedRangeMax - speedRangeMin);
		}

		particle.scale = Vector2.Scale (particle.originalScale, new Vector2 (scaleXBySpeed.getValue(t), scaleYBySpeed.getValue(t)));
	}
	#endregion

	#region - Param property
	public override void updateParams (PUEXParticleSystem system)
	{
		scaleXBySpeed.parameterize (system);
		scaleYBySpeed.parameterize (system);
	}
	#endregion

	#region - Serialization
	public override JsonData save (JsonData emitterData, JsonData systemData)
	{
		JsonData ret = base.save (emitterData, systemData);

		ret ["scale_x_by_speed"] = PUEXUtils.serializeDynamicAttribute (scaleXBySpeed);
		ret ["scale_y_by_speed"] = PUEXUtils.serializeDynamicAttribute (scaleYBySpeed);
		ret ["speed_range_min"] = speedRangeMin;
		ret ["speed_range_max"] = speedRangeMax;
		
		return ret;
	}
	#endregion

}
